package com.ruoyi.mp.service.impl;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.mp.domain.MpUser;
import com.ruoyi.mp.mapper.MpUserMapper;
import com.ruoyi.mp.service.IMpAccountService;
import com.ruoyi.mp.service.IMpUserService;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 公众号粉丝Service业务层处理
 *
 * @author ruoyi
 * @date 2023-11-18
 */
@Service
public class MpUserServiceImpl implements IMpUserService
{
    @Autowired
    private MpUserMapper mpUserMapper;
    @Autowired
    private WxMpService wxService;
    @Autowired
    private IMpAccountService iMpAccountService;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    //更新粉丝列表
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int insertListMpUser(List<MpUser> mpUsers) {
        if (mpUsers == null || mpUsers.isEmpty()) {
            return 0;
        }

        String appId = mpUsers.get(0).getAppId();
        if (this.mpUserMapper.selectCountAppId(appId) > 0) {
            synchronized (this) { // 加锁以避免并发问题
                if (this.mpUserMapper.selectCountAppId(appId) > 0) { // 双重检查锁定
                    this.mpUserMapper.deleteByAppId(appId);
                }
            }
        }

        // 使用批量插入提高性能
        return this.mpUserMapper.batchInsertMpUser(mpUsers);
    }

    /**
     * 查询公众号粉丝
     *
     * @param id 公众号粉丝主键
     * @return 公众号粉丝
     */
    @Override
    public MpUser selectMpUserById(Long id)
    {
        return mpUserMapper.selectMpUserById(id);
    }

    /**
     * 查询公众号粉丝列表
     *
     * @param mpUser 公众号粉丝
     * @return 公众号粉丝
     */
    @Override
    public List<MpUser> selectMpUserList(MpUser mpUser)
    {
        return mpUserMapper.selectMpUserList(mpUser);
    }

    /**
     * 新增公众号粉丝
     *
     * @param mpUser 公众号粉丝
     * @return 结果
     */
    @Override
    public int insertMpUser(MpUser mpUser)
    {
        mpUser.setCreateTime(DateUtils.getNowDate());
        return mpUserMapper.insertMpUser(mpUser);
    }

    /**
     * 修改公众号粉丝
     *
     * @param mpUser 公众号粉丝
     * @return 结果
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int updateMpUser(MpUser mpUser) throws WxErrorException {
        try {
            mpUser.setUpdateTime(DateUtils.getNowDate());
            MpUser mpUser1 =  mpUserMapper.selectMpUserById(mpUser.getId());
            // 更新粉丝昵称
            if (StringUtils.isNotEmpty(mpUser.getNickname())) {
                wxService.switchoverTo(mpUser.getAppId()).getUserService().userUpdateRemark(mpUser.getOpenid(), mpUser.getNickname());
            }
            if(StringUtils.isNotEmpty(mpUser.getTagIds())){
                // 使用正则表达式模式来匹配逗号，忽略尾随逗号
                if(StringUtils.isNotEmpty(mpUser1.getTagIds())){
                    String[] parts = mpUser1.getTagIds().split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
                    // 如果数组长度为 1，则表示没有逗号或只有一个值
                    for (String part : parts) {
                        long tagId = Long.parseLong(part.trim());
                        String openid = mpUser1.getOpenid();
                        String[] openids = new String[]{openid}; // 将单个openid转为String数组
                        wxService.switchoverTo(mpUser1.getAppId()).getUserTagService().batchUntagging(tagId,openids);
                    }
                }
                String[] tagIdList =  mpUser.getTagIds().split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
                for (String tag : tagIdList) {
                    long tagId = Long.parseLong(tag.trim());
                    String openid = mpUser.getOpenid();
                    String[] openids = new String[]{openid}; // 将单个openid转为String数组
                    wxService.switchoverTo(mpUser.getAppId()).getUserTagService().batchTagging(tagId,openids);
                }
            }

            return mpUserMapper.updateMpUser(mpUser);
        } catch (WxErrorException e) {
            // 处理微信SDK抛出的异常
            logger.info("Failed to update MP user: {}", e.getError().getErrorMsg(), e);
            throw e; // 或者可以根据业务需求选择返回一个错误码
        }
    }

    /**
     * 批量删除公众号粉丝
     *
     * @param ids 需要删除的公众号粉丝主键
     * @return 结果
     */
    @Override
    public int deleteMpUserByIds(Long[] ids)
    {
        return mpUserMapper.deleteMpUserByIds(ids);
    }

    /**
     * 删除公众号粉丝信息
     *
     * @param id 公众号粉丝主键
     * @return 结果
     */
    @Override
    public int deleteMpUserById(Long id)
    {
        return mpUserMapper.deleteMpUserById(id);
    }

    /**
     * 拉黑公众号粉丝
     *
     * @return 结果
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public  int blackFans(Long[] ids,Long accountId) throws WxErrorException {
        List<String> openidList  = mpUserMapper.selectOpenidList(ids);
        if(openidList.size() > 0){
            String appId = this.iMpAccountService.selectMpAccountById(accountId).getAppId();
                wxService.switchoverTo(appId).getBlackListService().pushToBlacklist(openidList);
            return pushToBlacklist(openidList,appId);
        }else{
            return 0;
        }
    }
    /**
     * 取消拉黑公众号粉丝
     *
     * @return 结果
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public  int cansleBlackFans(Long[] ids,Long accountId) throws WxErrorException {
        List<String> openidList  = mpUserMapper.selectOpenidList(ids);
        if(openidList.size() > 0){
            try {
                String appId = this.iMpAccountService.selectMpAccountById(accountId).getAppId();
                wxService.switchoverTo(appId).getBlackListService().pullFromBlacklist(openidList);
                return mpUserMapper.pullFromBlacklist(openidList,appId);
            }catch (WxErrorException e){
                logger.info("Failed to update MP user: {}", e.getError().getErrorMsg(), e);
                throw  e;
            }catch (Exception e){
                logger.info("Failed to update MP user: {}", e.getMessage());
                throw  e;
            }
        }else{
            logger.info("没有查询到openid");
            return 0;
        }
    }
    /**
     * 批量插入黑名单
     *
     * @return 结果
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int  pushToBlacklist(List<String> openidList,String appId){
        try{
            mpUserMapper.deleteMpUserBlackByAppid(appId);
            return  mpUserMapper.pushToBlacklist(openidList,appId);
        }catch (Exception e){
            logger.info("Failed to update MP user: {}", e.getMessage());
            throw  e;
        }
    }
}
